#!/usr/bin/expect

#起始 和结束 ip
set command [lindex $argv 0]
set start [lindex $argv 1]
set end [lindex $argv 2]

set SINGLE_HOST 192.168.73.10;  #单个服务执行
set BATCH_PRE 192.168.73;     #多个服务器前缀
set USER admin
set PASSWORD admin123

#源文件或者目录
set SRC_FILE /Users/mac/expect/option
#目标目录
set TARGET_FILE /home/dave/soft/
#主机列表
set ips {}





#start
proc start {} {
	send_user -- "\t _______           _______  _______  _______ _________\n";
	send_user -- "\t(  ____ \\|\\     /|(  ____ )(  ____ \\(  ____ \\\\__   __/\n";
	send_user -- "\t| (    \\/( \\   / )| (    )|| (    \\/| (    \\/   ) (  \n";
	send_user -- "\t| (__     \\ (_) / | (____)|| (__    | |         | |   \n";
	send_user -- "\t|  __)     ) _ (  |  _____)|  __)   | |         | |  \n";
	send_user -- "\t| (       / ( ) \\ | (      | (      | |         | | \n";
	send_user -- "\t| (____/\\( /   \\ )| )      | (____/\\| (____/\\   | |   \n";
	send_user -- "\t(_______/|/     \\||/       (_______/(_______/   )_(  \n";

}

#生成的IP信息
proc info {} {
    global ips 
    set count [llength $ips]
    set final [expr {$count-1}]
    puts "生成的地址列表个数：$count,[lindex $ips 0]--->[lindex $ips $final]"
}

#SCP
proc doScp {} {
    global ips
    set timeout 10
    #执行scp
    foreach ip $ips {
      spawn scp -r $::SRC_FILE $::USER@$ip:$::TARGET_FILE
         expect {
             "*yes/no*" {
                send "yes\r";exp_continue;
             }
             "*password:*" {
                send "$::PASSWORD\r";exp_continue;
            }
             "*permission denied*" {
                send_user "copy $::SRC_FILE to $::TARGET_FILE in $ip is fail\n"
            }
             eof {
                send_user "copy $::SRC_FILE to  $::TARGET_FILE in $ip is success\n"
            }
        }
    }
    exit
}

#生成连续的ip地址
proc initHost {} {
    global ips
    for {set index $::start} {$index < $::end} {incr index} {
        lappend ips $::BATCH_PRE.$index
    }
}

#执行的操作
proc doOption {param} {
    global ips
    switch $param {
        -s {
            puts "execute single"
            lappend ips $::SINGLE_HOST 
            info
            doScp
        }
        -b {
            if {$::argc < 3} {
                puts "请正确执行指令: expect $::argv0 command start end"
                 exit
            }
            puts "execute batch"
            initHost
            info
            doScp
        }
        default {
             #使用命令
             puts "useage: expect $::argv0 -s to single scp"    
             puts "useage: expect $::argv0 -b to batch scp"
        }
    }
}


##############STAR##########
start
doOption $command
##############END###########






